package com.data;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jplus.core.db.JdbcTemplate;
import com.jplus.core.utill.HttpClientUtil;
import com.jplus.core.utill.SimpleSql;
import com.jplus.core.utill.StreamUtil;
import com.kit.IDCardKit;
import com.kit.IDCardKit.IDCard;
import com.kit.IDCardKit.STATUS;

/**
 * http://www.mca.gov.cn/article/sj/xzqh/
 * 
 * http://idcard.miaochaxun.com/
 * 
 * http://www.ip33.com/area_code.html
 * 
 * @author Yuanqy
 *
 */
public class IDCardUtil {
	private IDCardKit kit;

	private Set<Integer> set = new HashSet<>();
	Properties prop = new Properties();
	JdbcTemplate jdbc;
	SimpleSql sql;

	public static void main(String[] args) throws Exception {
		// new IDCardUtil();
		new IDCardUtil().addCard();
	}

	public IDCardUtil() throws Exception {
		super();
		prop.load(new FileInputStream(new File("D:/config/jplus-mvc.properties")));
		jdbc = new JdbcTemplate(GET(prop, "dataSource.jdbcUrl"), GET(prop, "dataSource.username"),
				GET(prop, "dataSource.password"));
		kit = new IDCardKit();
	}

	public void getArea(int area) throws InterruptedException {
		if (!set.contains(area)) {
			set.add(area);
			HttpClientUtil http = new HttpClientUtil();
			String html = http.doGet("http://idcard.miaochaxun.com/" + area + ".html");
			Matcher m = Pattern.compile("<title>(.*?)</title>").matcher(html);
			while (m.find()) {
				String[] sp = m.group().split("-");
				System.err.println(area + "," + sp[2] + "," + (area - area % 100));
			}
			Thread.sleep(1000);
		}
	}

	public void addCard() {
		List<String> list = StreamUtil.toReadFileLine(new File("D:\\IDCard.csv"));
		for (String str : list) {
			try {
				String[] line = str.split(",");
				String cardNo = line[1].trim().toUpperCase();
				String userName = line[0].trim();
				IDCard ic = kit.doCheck(cardNo);
				if (cardNo.length() != 18)
					continue;
				if (ic.getStatus() == STATUS.SUCC) {
					jdbc.execute(
							"INSERT INTO  `sys_id_card` (`card_code`,`card_name`,`area_code`,`sex`,`age`) VALUES(?,?,?,?,?)",
							cardNo, userName, ic.getAreaCode(), ic.getSex().equals("男") ? 1 : 0, ic.getBirthday());
				} else {
					System.err.println(ic);
				}

			} catch (Exception e) {
				System.err.println(e.getMessage());
			}
		}
	}

	String GET(Properties prop, String key) {
		return prop.getProperty(key).trim();
	}

}
